package com.springboot.astra.myInterceptor;

import com.springboot.astra.bean.User;
import com.springboot.astra.myEcxeption.TokenException;
import com.springboot.astra.result.DataResult;
import com.springboot.astra.service.UserService;
import com.springboot.astra.util.DateUtils;
import com.springboot.astra.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(request.getRequestURL());
        System.out.println(request.getRequestURI());
        String token = request.getHeader("Authorization");// 从 http 请求头中取出 token
        System.out.println(token);
        if (token!=null){
            //验证token
            Claims claims = jwtUtils.parseJwt(token);
            //判断token是否过期
            if (DateUtils.isOverTime(claims.getExpiration()) ){
                //token 有效
                try {
                    //验证用户信息是否正常
                    User user = userService.getOneById(Integer.valueOf(claims.getId()));
                    if (user.getUserAccount().equals(claims.getSubject())){
                        //进入controller,验证成功，是自己人
                        return true;
                    }else {
                        //返回错误信息
                        setHttpServletResponse(request,response);
                        throw new TokenException("您的验证信息无效");
                    }
                }catch (NullPointerException e){
                    setHttpServletResponse(request,response);
                    throw new TokenException("无效的验证信息");
                }

            }else{
                //如果失效了,返回token 超时
                setHttpServletResponse(request,response);
                throw new TokenException("登录已失效，请从新登录");
            }
        }
        //返回 无效的token
        setHttpServletResponse(request,response);
        throw new TokenException("无效的验证信息");
    }

    /**
     * 向浏览器返回信息
     * @param response
     * @param data
     * @throws Exception
     */
    private void returnData(HttpServletResponse response, DataResult data) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null)
                writer.close();
        }
    }
    private void setHttpServletResponse (HttpServletRequest request, HttpServletResponse response){
        //拦截器跨域请求设置
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    }

}
